/*
 * $HeadURL:  $
 *
 * Copyright (c) 2007 Drutt Corporation, all rights reserved.
 *
 */
package homework.james.xiao.util;

/**
 * @author eyngxao
 * @version $Revision: $
 */
public class ByteComput {

	/** Class revision */
	public static final String _REV_ID_ = "$Revision: $";

	public static void main(String[] args){
		String x = "1011011";
		String y = "0011000";
		int a = binaryStringToInt(x);
		int b = binaryStringToInt(y);
		System.out.println("a: " + intToBinaryString(a));
		System.out.println("b: " + intToBinaryString(b));
		System.out.println("Conflicted: " + isConflict(a,b));
		System.out.println("Contains: " + contains(a, b));
	}
	/**
	 * return true if schedule a contains schedule b
	 * @return
	 * @author eyngxao
	 */
	private static boolean contains(int a, int b){
		String x = intToBinaryString(a);
		String y = intToBinaryString(b);
		for (int i=0;i<x.length();i++){
			if (x.charAt(i)=='0' && y.charAt(i)=='1')
				return false;
		}
		return true;
	}
	/**
	 * return true if schedule a is confilcted with schedule b
	 * @param a
	 * @param b
	 * @return
	 * @author eyngxao
	 */
	private static boolean isConflict(int a, int b){
		return !((~a | ~b)==-1);
	}
	
	private static String intToBinaryString(int i) throws RuntimeException{
		if (i>127){
			throw new RuntimeException("Value " + i + "is out of range!");
		}
		String a = Integer.toBinaryString(i);
		int l =a.length();
		String padding = createPadding(7-l);
		return padding + a;
	}

	/**
	 * @param i
	 * @return
	 * @author eyngxao  
	 */
	private static String createPadding(int j) {
		StringBuilder padding = new StringBuilder();
		for (int i=0;i<j;i++)
			padding.append("0");
		return padding.toString();
	}
	
	private static int binaryStringToInt(String s){
		int result = 0;
		int length = s.length();
		for (int i=0;i<length;i++){
			if (s.charAt(i)=='1')
				result += 1<<(length-i-1);
			else if (s.charAt(i)!='0')
				throw new RuntimeException("Invalid Binary String!");
		}
		return result;
		
	}
}
